<template>
  <div class="payment-page">
    <el-card class="payment-card">
      <template #header>
        <div class="card-header">
          <h3>订单支付</h3>
          <div class="countdown" v-if="countdown > 0">
            <span>支付剩余时间：</span>
            <span class="time">{{ formatCountdown(countdown) }}</span>
          </div>
        </div>
      </template>

      <div v-loading="loading" class="payment-content">
        <!-- 订单信息 -->
        <div class="order-section">
          <h4>订单信息</h4>
          <el-card class="order-info-card" shadow="never">
            <el-row :gutter="20">
              <el-col :span="4">
<!--                <img :src="orderInfo.carImage || '/default-car.jpg'" alt="车辆图片" class="car-image">-->
                <img :src="`/api/file/download.do?filename=${orderInfo.carImage}`"
                     :alt="车辆图片" class="car-image" />
              </el-col>
              <el-col :span="20">
                <div class="order-details">
                  <h5>{{ orderInfo.carBrand }} {{ orderInfo.carModel }}</h5>
                  <p>订单号：{{ orderInfo.id }}</p>
                  <p>车牌号：{{ orderInfo.licensePlate }}</p>
                  <p>租车时间：{{ formatDate(orderInfo.startTime) }} 至 {{ formatDate(orderInfo.endTime) }}</p>
                  <p>租车天数：{{ orderInfo.rentDays }} 天</p>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </div>

        <!-- 费用明细 -->
        <div class="cost-section">
          <h4>费用明细</h4>
          <el-card class="cost-card" shadow="never">
            <div class="cost-item">
              <span>日租金</span>
              <span>¥{{ orderInfo.dailyRent }}/天</span>
            </div>
            <div class="cost-item">
              <span>租车天数</span>
              <span>{{ orderInfo.rentDays }} 天</span>
            </div>
            <el-divider></el-divider>
            <div class="cost-item total">
              <span>应付金额</span>
              <span class="total-amount">¥{{ orderInfo.estimatedTotalAmount }}</span>
            </div>
          </el-card>
        </div>

        <!-- 支付方式 -->
        <div class="payment-method-section">
          <h4>选择支付方式</h4>
          <el-radio-group v-model="selectedPaymentMethod" class="payment-methods">
            <div class="payment-option-wrapper" :class="{ 'selected': selectedPaymentMethod === '1' }">
              <el-radio label="1">
                <div class="payment-item">
                  <el-icon class="payment-icon wechat-icon" size="32">
                    <ChatDotRound />
                  </el-icon>
                  <div class="payment-info">
                    <div class="payment-name">微信支付</div>
                    <div class="payment-desc">推荐使用微信支付</div>
                  </div>
                </div>
              </el-radio>
            </div>
            <div class="payment-option-wrapper" :class="{ 'selected': selectedPaymentMethod === '2' }">
              <el-radio label="2">
                <div class="payment-item">
                  <el-icon class="payment-icon alipay-icon" size="32">
                    <CreditCard />
                  </el-icon>
                  <div class="payment-info">
                    <div class="payment-name">支付宝</div>
                    <div class="payment-desc">安全便捷的支付方式</div>
                  </div>
                </div>
              </el-radio>
            </div>
          </el-radio-group>
        </div>

        <!-- 支付按钮 -->
        <div class="payment-actions">
          <div class="amount-display">
            <span>应付金额：</span>
            <span class="amount">¥{{ orderInfo.estimatedTotalAmount }}</span>
          </div>
          <div class="action-buttons">
            <el-button @click="goBack">返回</el-button>
            <el-button type="primary" size="large" @click="processPayment" :loading="paying">
              支付
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 支付结果对话框 -->
    <el-dialog v-model="resultDialogVisible" title="支付结果" width="400px" :close-on-click-modal="false">
      <div class="payment-result">
        <div v-if="paymentSuccess" class="success-result">
          <el-icon class="success-icon" size="60" color="#67c23a">
            <SuccessFilled />
          </el-icon>
          <h3>支付成功！</h3>
          <p>您的订单已支付成功，请按时取车。</p>
        </div>
        <div v-else class="failed-result">
          <el-icon class="failed-icon" size="60" color="#f56c6c">
            <CircleCloseFilled />
          </el-icon>
          <h3>支付失败</h3>
          <p>{{ paymentErrorMessage }}</p>
        </div>
      </div>
      <template #footer>
        <div class="result-actions">
          <el-button v-if="!paymentSuccess" @click="resultDialogVisible = false">重新支付</el-button>
          <el-button v-if="paymentSuccess" type="primary" @click="goToOrders">查看订单</el-button>
          <el-button v-if="paymentSuccess" @click="goToBrowse">继续租车</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { SuccessFilled, CircleCloseFilled, ChatDotRound, CreditCard } from '@element-plus/icons-vue'
import { getRentalDetail } from '@/api/rental'
import { simulatePayment } from '@/api/paymentSimulation'
import { useUserInfoStore } from '@/stores/userInfo'

const route = useRoute()
const router = useRouter()
const userInfoStore = useUserInfoStore()

// 数据
const loading = ref(false)
const paying = ref(false)
const countdown = ref(1800) // 30分钟倒计时
const selectedPaymentMethod = ref('1')

// 订单信息
const orderInfo = reactive({
  id: route.params.orderId,
  carBrand: '',
  carModel: '',
  licensePlate: '',
  startTime: '',
  endTime: '',
  rentDays: '',
  dailyRent: '',
  estimatedTotalAmount: '',
  carImage: ''
})

// 支付结果
const resultDialogVisible = ref(false)
const paymentSuccess = ref(false)
const paymentErrorMessage = ref('')

// 定时器
let countdownTimer = null

// 方法
const loadOrderInfo = async () => {
  loading.value = true

  try {
    // 调用真实API获取订单详情
    const response = await getRentalDetail({
      rentalId: orderInfo.id,
      userId: userInfoStore.userInfo?.id || ''
    })

    // 更新订单信息
    if (response && response.data) {
      const order = response.data
      Object.assign(orderInfo, {
        carBrand: order.brand || '未知品牌',
        carModel: order.model || '未知型号',
        licensePlate: order.licensePlate || '未知车牌',
        startTime: new Date(order.startTime),
        endTime: new Date(order.endTime),
        rentDays: order.rentDays || '0',
        dailyRent: order.dailyRent || '0',
        estimatedTotalAmount: order.estimatedTotalAmount || '0',
        carImage: order.images ? order.images.split(',')[0] : '/car-images/default.jpg'
      })
    }

  } catch (error) {
    ElMessage.error('加载订单信息失败')
    console.error('加载订单信息失败:', error)

    // 如果API失败，使用默认数据
    Object.assign(orderInfo, {
      carBrand: '未知品牌',
      carModel: '未知型号',
      licensePlate: '未知车牌',
      startTime: new Date(),
      endTime: new Date(),
      rentDays: '1',
      dailyRent: '200',
      estimatedTotalAmount: '200',
      carImage: '/car-images/default.jpg'
    })
  } finally {
    loading.value = false
  }
}

const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.getFullYear() + '-' + 
         String(d.getMonth() + 1).padStart(2, '0') + '-' + 
         String(d.getDate()).padStart(2, '0')
}

const formatCountdown = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`
}

const startCountdown = () => {
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer)
      ElMessage.warning('支付超时，请重新下单')
      router.push('/user/rental/orders')
    }
  }, 1000)
}

const processPayment = async () => {
  paying.value = true

  try {
    // 调用真实支付API
    const response = await simulatePayment({
      orderId: orderInfo.id,
      userId: userInfoStore.userInfo?.id || '1', // 从用户状态获取真实用户ID
      paymentType: selectedPaymentMethod.value,
      amount: orderInfo.estimatedTotalAmount
    })

    // 由于request拦截器已经处理了成功响应，这里直接使用数据
    paymentSuccess.value = response.data.success
    if (!response.data.success) {
      paymentErrorMessage.value = response.data.message || '支付失败，请检查支付方式或稍后重试'
    }

    resultDialogVisible.value = true

    if (paymentSuccess.value) {
      // 停止倒计时
      if (countdownTimer) {
        clearInterval(countdownTimer)
      }
    }
    
  } catch (error) {
    ElMessage.error('支付处理失败')
    console.error('支付处理失败:', error)
  } finally {
    paying.value = false
  }
}

const goBack = () => {
  router.back()
}

const goToOrders = () => {
  router.push('/user/rental/orders')
}

const goToBrowse = () => {
  router.push('/user/carBrowse')
}

// 生命周期
onMounted(() => {
  loadOrderInfo()
  startCountdown()
})

onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>

<style scoped>
.payment-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.payment-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
}

.countdown {
  color: #e6a23c;
  font-weight: bold;
}

.countdown .time {
  font-size: 18px;
}

.payment-content {
  padding: 20px 0;
}

.order-section,
.cost-section,
.payment-method-section {
  margin-bottom: 30px;
}

.order-section h4,
.cost-section h4,
.payment-method-section h4 {
  margin-bottom: 15px;
  color: #303133;
}

.order-info-card,
.cost-card {
  background: #f8f9fa;
}

.car-image {
  width: 100%;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
}

.order-details h5 {
  margin: 0 0 10px 0;
  color: #303133;
}

.order-details p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.cost-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #606266;
}

.cost-item.total {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.total-amount {
  color: #e6a23c;
  font-size: 18px;
}

.payment-methods {
  width: 100%;
  display: flex;
  flex-direction: row;
  gap: 20px;
  justify-content: center;
}

.payment-option-wrapper {
  border: 2px solid #dcdfe6;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
  background: #fff;
  cursor: pointer;
  flex: 1;
  max-width: 300px;
  min-width: 200px;
}

.payment-option-wrapper:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.payment-methods .el-radio {
  width: 100%;
  margin: 0;
  height: auto;
}

/* 选中状态样式 */
.payment-option-wrapper.selected {
  border-color: #409eff !important;
  background: #f0f9ff !important;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2) !important;
}

.payment-methods .el-radio__input {
  position: absolute;
  top: 20px;
  right: 20px;
}

.payment-methods .el-radio__label {
  width: 100%;
  padding: 0;
  display: block;
}

.payment-item {
  display: flex;
  align-items: center;
  width: 100%;
}

.payment-icon {
  margin-right: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.wechat-icon {
  color: #07c160;
}

.alipay-icon {
  color: #1677ff;
}

.payment-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.payment-name {
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
  font-size: 16px;
}

.payment-desc {
  color: #909399;
  font-size: 13px;
  line-height: 1.4;
}

.payment-actions {
  margin-top: 40px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.amount-display {
  text-align: center;
  margin-bottom: 20px;
}

.amount-display .amount {
  color: #e6a23c;
  font-size: 24px;
  font-weight: bold;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.action-buttons .el-button {
  min-width: 100px;
  height: 40px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .payment-methods {
    flex-direction: column;
    gap: 15px;
  }

  .payment-option-wrapper {
    max-width: none;
    min-width: auto;
  }
}

.payment-result {
  text-align: center;
  padding: 20px;
}

.success-result h3,
.failed-result h3 {
  margin: 20px 0 10px 0;
}

.success-result p,
.failed-result p {
  color: #606266;
  margin-bottom: 20px;
}

.result-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
}
</style>
